﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Events.Bus;
using Abp.Extensions;
using Abp.Linq.Extensions;
using ARchGL.Platform.Core;
using ARchGL.Platform.EventHandlers.Events;
using ARchGL.Platform.Qianbian;
using ARchGL.Platform.Qianbian.InputModels;
using ARchGL.Platform.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApiClient;

namespace ARchGL.Platform.Application
{
    /// <summary>
    /// 千变智慧工地 实现
    /// </summary>
    public class QianbianAppService : PlatformAppServiceBase, IQianbianAppService
    {
        #region 实例化
        private const int _Days = -1;

        private readonly IProjectInfoApi projectInfoApi;
        private readonly IRepository<QB_Projects, Guid> qb_projectsRepository;
        private readonly IRepository<QB_ProjectUsers, Guid> qb_projectUsersRepository;
        private readonly IRepository<QB_ProjectVideos, Guid> qb_projectVideosRepository;
        private readonly IRepository<QB_ProjectVideoPlays, Guid> qb_projectVideoPlaysRepository;
        private readonly IRepository<QB_ProjectCranes, Guid> qb_projectCranesRepository;
        private readonly IRepository<QB_ProjectDevices, Guid> qb_projectDevicesRepository;
        private readonly IRepository<QB_ProjectAttendances, Guid> qb_projectAttendancesRepository;
        private readonly IRepository<QB_ProjectLifts, Guid> qb_projectLiftsRepository;
        private readonly IRepository<QB_ProjectEnvironments, Guid> qb_projectEnvironmentsRepository;
        private static TimerCache<bool> RequestAsyncCache = new TimerCache<bool>();
        private static TimerCache<bool> RequestClearCache = new TimerCache<bool>();
        //private static TimerCache<List<QB_QueryProjectAttendanceReportDto>> ProjectAttendanceCache = new TimerCache<List<QB_QueryProjectAttendanceReportDto>>();
        private static Dictionary<DateTime, List<QB_QueryProjectAttendanceReportDto>> ProjectAttendanceCache = new Dictionary<DateTime, List<QB_QueryProjectAttendanceReportDto>>();

        public IEventBus EventBus { get; set; }
        public QianbianAppService(
            IProjectInfoApi _projectInfoApi,
            IRepository<QB_Projects, Guid> _qb_projectsRepository,
            IRepository<QB_ProjectUsers, Guid> _db_projectUsersRepository,
            IRepository<QB_ProjectVideos, Guid> _db_projectVideosRepository,
            IRepository<QB_ProjectVideoPlays, Guid> _qb_projectVideoPlaysRepository,
            IRepository<QB_ProjectDevices, Guid> _db_projectDevicesRepository,
            IRepository<QB_ProjectAttendances, Guid> _qb_projectAttendancesRepository,
            IRepository<QB_ProjectLifts, Guid> _qb_projectLiftsRepository,
            IRepository<QB_ProjectCranes, Guid> _qb_projectCranesRepository,
            IRepository<QB_ProjectEnvironments, Guid> _qb_projectEnvironmentsRepository)
        {
            projectInfoApi = _projectInfoApi;
            qb_projectsRepository = _qb_projectsRepository;
            qb_projectUsersRepository = _db_projectUsersRepository;
            qb_projectVideosRepository = _db_projectVideosRepository;
            qb_projectVideoPlaysRepository = _qb_projectVideoPlaysRepository;
            qb_projectDevicesRepository = _db_projectDevicesRepository;
            qb_projectAttendancesRepository = _qb_projectAttendancesRepository;
            qb_projectLiftsRepository = _qb_projectLiftsRepository;
            qb_projectCranesRepository = _qb_projectCranesRepository;
            qb_projectEnvironmentsRepository = _qb_projectEnvironmentsRepository;
        }

        #endregion

        #region 第三方内部接口（内部使用或 Swagger 快速调试，外部禁止调用）

        /// <summary>
        /// 获取企业项目档案
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="index">KeyId下标</param>
        /// <returns></returns>
        public ITask<AjaxResponse<List<ProjectsApiDto>>> GetProjectPagedList(int page, int index)
        {
            return projectInfoApi.GetProjectPagedList(page, index);
        }

        /// <summary>
        /// 获取项目成员档案
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="projectId">项目标识</param>
        /// <param name="index">KeyId下标</param>
        /// <returns></returns>
        public ITask<AjaxResponse<List<ProjectUsersApiDto>>> GetProjectUserPagedList(int page, Guid projectId, int index)
        {
            return projectInfoApi.GetProjectUserPagedList(page, projectId, index);
        }

        /// <summary>
        /// 获取项目设备档案
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="projectId">项目标识</param>
        /// <param name="index">KeyId下标</param>
        /// <returns></returns>
        public ITask<AjaxResponse<List<ProjectDevicesApiDto>>> GetProjectDevicePagedList(int page, Guid projectId, int index)
        {
            return projectInfoApi.GetProjectDevicePagedList(page, projectId, index);
        }

        /// <summary>
        /// 获取项目考勤数据
        /// </summary>
        /// <param name="day">格式为yyyy-MM-dd，默认为当天</param>
        /// <param name="page">页码</param>
        /// <param name="projectId">项目标识</param>
        /// <param name="index">KeyId下标</param>
        /// <returns></returns>
        public ITask<AjaxResponse<List<ProjectAttendancesApiDto>>> GetProjectAttendancePagedList(string day, int page, Guid projectId, int index)
        {
            return projectInfoApi.GetProjectAttendancePagedList(day, page, projectId, index);
        }

        /// <summary>
        /// 获取项目环境监控数据
        /// </summary>
        /// <param name="startTime">格式为yyyy-MM-dd</param>
        /// <param name="endTime">格式为yyyy-MM-dd</param>
        /// <param name="page">页码</param>
        /// <param name="projectId">项目标识</param>
        /// <param name="serialNumber">设备序列号</param>
        /// <param name="index">KeyId下标</param>
        /// <returns></returns>
        public ITask<AjaxResponse<List<ProjectEnvironmentsApiDto>>> GetProjectsEnvironmentPagedList(DateTime? startTime, DateTime? endTime, int page, Guid projectId, string serialNumber, int index)
        {
            long start = startTime.HasValue ? startTime.Value.ToUnixTimestamp() : DateTime.Now.AddDays(_Days).ToUnixTimestamp();
            long end = endTime.HasValue ? endTime.Value.ToUnixTimestamp() : DateTime.Now.ToUnixTimestamp();
            return projectInfoApi.GetProjectsEnvironmentPagedList(start, end, page, projectId, serialNumber, index);
        }

        /// <summary>
        /// 获取项目塔吊运行数据
        /// </summary>
        /// <param name="startTime">格式为yyyy-MM-dd</param>
        /// <param name="endTime">格式为yyyy-MM-dd</param>
        /// <param name="page">页码</param>
        /// <param name="projectId">项目标识</param>
        /// <param name="serialNumber">黑匣子设备序列号</param>
        /// <param name="index">KeyId下标</param>
        /// <returns></returns>
        public ITask<AjaxResponse<List<ProjectCranesApiDto>>> GetProjectsCranePagedList(DateTime? startTime, DateTime? endTime, int page, Guid projectId, string serialNumber, int index)
        {
            long start = startTime.HasValue ? startTime.Value.ToUnixTimestamp() : DateTime.Now.AddDays(_Days).ToUnixTimestamp();
            long end = endTime.HasValue ? endTime.Value.ToUnixTimestamp() : DateTime.Now.ToUnixTimestamp();
            return projectInfoApi.GetProjectsCranePagedList(start, end, page, projectId, serialNumber, index);
        }

        /// <summary>
        /// 获取项目施工升降机运行数据
        /// </summary>
        /// <param name="startTime">格式为yyyy-MM-dd</param>
        /// <param name="endTime">格式为yyyy-MM-dd</param>
        /// <param name="page">0</param>
        /// <param name="projectId">项目标识</param>
        /// <param name="serialNumber">黑匣子设备序列号</param>
        /// <param name="index">KeyId下标</param>
        /// <returns></returns>
        public ITask<AjaxResponse<List<ProjectLiftsApiDto>>> GetProjectsLiftPagedList(DateTime? startTime, DateTime? endTime, int page, Guid projectId, string serialNumber, int index)
        {
            long start = startTime.HasValue ? startTime.Value.ToUnixTimestamp() : DateTime.Now.AddDays(_Days).ToUnixTimestamp();
            long end = endTime.HasValue ? endTime.Value.ToUnixTimestamp() : DateTime.Now.ToUnixTimestamp();
            return projectInfoApi.GetProjectsLiftPagedList(start, end, page, projectId, serialNumber, index);
        }

        /// <summary>
        /// 获取项目视频监控摄像头数据
        /// </summary>
        /// <param name="projectId">项目标识</param>
        /// <param name="index">KeyId下标</param>
        /// <returns></returns>
        public ITask<AjaxResponse<List<ProjectVideosApiDto>>> GetProjectsVideoList(Guid projectId, int index)
        {
            return projectInfoApi.GetProjectsVideoList(projectId, index);
        }

        /// <summary>
        /// 根据摄像头获取播放地址
        /// </summary>
        /// <param name="projectId">项目标识</param>
        /// <param name="videoId">视频标识</param>
        /// <param name="index">KeyId下标</param>
        /// <returns></returns>
        public ITask<AjaxResponse<ProjectVideoPlaysApiDto>> GetProjectsVideoPlay(Guid projectId, Guid videoId, int index)
        {
            return projectInfoApi.GetProjectsVideoPlay(projectId, videoId, index);
        }

        #endregion

        #region 第三放外部接口

        /// <summary>
        /// 获取企业项目档案
        /// </summary>
        /// <param name="input">分页</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<PagedResultDto<QB_Projects>> QueryProjectPagedList(QB_ProjectInput input)
        {
            var projectQuery = qb_projectsRepository.GetAll();

            var result = await projectQuery
                .WhereIf(!input.Code.IsNullOrWhiteSpace(), x => x.Code == input.Code)
                .OrderByDescending(x => x.CreationTime).PageByAsync(input);

            return new PagedResultDto<QB_Projects>(projectQuery.Count(),
                ObjectMapper.Map<List<QB_Projects>>(result));
        }

        /// <summary>
        /// 获取项目成员档案
        /// </summary>
        /// <param name="input">分页</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<PagedResultDto<QB_ProjectUsers>> QueryProjectUserPagedList(QB_ProjectUsersInput input)
        {
            var typeList = new string[] { "JL", "SG" };
            var query = qb_projectUsersRepository.GetAll().Where(x => x.ProjectId == input.ProjectId)
                        .WhereIf(input.Type == 1, x => typeList.Contains(x.Type))
                        .WhereIf(input.Type == 2, x => !typeList.Contains(x.Type))
                        .WhereIf(!input.Filter.IsNullOrWhiteSpace(), x => x.RealName.Contains(input.Filter));

            var result = await query.OrderByDescending(x => x.CreationTime).PageByAsync(input);

            return new PagedResultDto<QB_ProjectUsers>(query.Count(),
                ObjectMapper.Map<List<QB_ProjectUsers>>(result));
        }

        /// <summary>
        /// 获取项目设备档案
        /// </summary>
        /// <param name="input">分页</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<PagedResultDto<QB_ProjectDevices>> QueryProjectDevicePagedList(QB_ProjectDevicesInput input)
        {
            var query = qb_projectDevicesRepository.GetAll().Where(x => x.ProjectId == input.ProjectId)
                        .WhereIf(!input.Filter.IsNullOrWhiteSpace(), x => x.SN.Contains(input.Filter) || x.CertNo.Contains(input.Filter)
                        || x.Alias.Contains(input.Filter) || x.SNRight.Contains(input.Filter) || x.AliasRight.Contains(input.Filter));

            var result = await query.OrderByDescending(x => x.CreationTime).PageByAsync(input);

            return new PagedResultDto<QB_ProjectDevices>(query.Count(),
                ObjectMapper.Map<List<QB_ProjectDevices>>(result));
        }

        /// <summary>
        /// 获取项目考勤数据
        /// </summary>
        /// <param name="input">分页</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<PagedResultDto<QB_QueryProjectAttendancePagedListDto>> QueryProjectAttendancePagedList(QB_ProjectAttendancesInput input)
        {
            var result = new List<QB_QueryProjectAttendancePagedListDto>();
            var projectAttendancesQuery = (from pa in qb_projectAttendancesRepository.GetAll()
                                           where pa.ProjectId == input.ProjectId && pa.AttendanceTime.Date == input.Date.Date//查询指定日期
                                           select pa).ToList();

            var projectUserIdList = projectAttendancesQuery.Select(x => x.IdCardSHA).Distinct().ToList();
            var projectUsersQuery = qb_projectUsersRepository.GetAll().Where(x => projectUserIdList.Contains(x.IdCardSHA))
                                    .WhereIf(!input.Type.IsNullOrWhiteSpace(), x => x.Type == input.Type);

            var count = projectUsersQuery.Count();
            var projectUsersList = (await projectUsersQuery.OrderBy(x => x.RealName).PageByAsync(input)).ToList();

            foreach (var item in projectUsersList)
            {
                if (result.Any(x => x.Name == item.RealName)) continue;
                var list = projectAttendancesQuery.Where(x => x.IdCardSHA == item.IdCardSHA).OrderBy(x => x.AttendanceTime);
                var entity = new QB_QueryProjectAttendancePagedListDto(item.RealName, item.TypeName)
                {
                    InTime = list?.FirstOrDefault(x => x.Entry == 1)?.AttendanceTime,
                    OutTime = list?.LastOrDefault(x => x.Entry == -1)?.AttendanceTime,
                };
                result.Add(entity);
            }

            return new PagedResultDto<QB_QueryProjectAttendancePagedListDto>(count, result);
        }

        /// <summary>根据人员类别获取下标</summary>
        private int GetIndex(string type)
        {
            switch (type)
            {
                case "JL": return 0; //监理单位
                case "SG": return 1; //施工单位
                case "ZY": return 2; //作业工人
                default: return 2;
            }
        }

        /// <summary>
        /// 获取项目考勤月统计报表，数组中的顺序：0监理单位，1施工单位，2作业工人
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<List<QB_QueryProjectAttendanceReportDto>> QueryProjectAttendanceReport(QB_QueryProjectAttendanceReportInput input)
        {
            var currentMonth = input.Date.ToString("yyyy-MM");
            var currentDate = DateTime.Parse(currentMonth + DateTime.Now.ToString("-dd HH:mm:ss"));
            var keys = new List<DateTime>(ProjectAttendanceCache.Keys);
            foreach (var item in keys)
            {
                if (item.ToString("yyyy-MM") != input.Date.ToString("yyyy-MM")) continue;

                if (item > currentDate)
                    return ProjectAttendanceCache[item];
                else ProjectAttendanceCache.Remove(item);
            }

            var result = new List<QB_QueryProjectAttendanceReportDto>();
            var firstDay = DateTime.Parse(currentMonth + "-01");
            for (int i = 0; i < 40; i++)
            {
                var day = firstDay.AddDays(i);
                if ((day.Year == DateTime.Now.Year && day.Month == DateTime.Now.Month && day.Day > DateTime.Now.Day) || //本年度当月只返回至当天的考勤
                    day.Month != firstDay.Month || //返回整月数据时，一直累加至跨月
                    (day.Year == DateTime.Now.Year && day.Month > DateTime.Now.Month) //本年度月份大于当前日期时，不返回手术
                    ) break;
                result.Add(new QB_QueryProjectAttendanceReportDto(day.Day, new int[3]));
            }
            if (!result.Any()) return await Task.FromResult(result);

            var projectAttendancesList = (from pa in qb_projectAttendancesRepository.GetAll()
                                          where pa.ProjectId == input.ProjectId &&
                                          pa.AttendanceTime.Year == input.Date.Year && pa.AttendanceTime.Month == input.Date.Month
                                          select new { pa.AttendanceTime, pa.IdCardSHA }).ToList();

            var idList = projectAttendancesList.Select(x => x.IdCardSHA).Distinct().ToList();
            var userList = await qb_projectUsersRepository.GetAllListAsync(x => idList.Contains(x.IdCardSHA));

            var dict = new Dictionary<string, bool>();
            foreach (var item in projectAttendancesList)
            {
                var day = result.FirstOrDefault(x => x.Day == item.AttendanceTime.Day);
                if (day == null) continue;
                var user = userList.FirstOrDefault(x => x.IdCardSHA == item.IdCardSHA);
                var key = item.AttendanceTime.Day + item.IdCardSHA + user?.Id;
                if (dict.ContainsKey(key)) continue;

                dict.Add(key, true);
                day.Array[GetIndex(user?.Type)] += 1;
            }
            ProjectAttendanceCache.TryAdd(currentDate.AddMinutes(3), result); //缓存3分钟，因为考勤同步周期是5分钟
            return await Task.FromResult(result);
        }

        /// <summary>获取项目当前环境监控数据，统计报表</summary>
        [AbpAuthorize]
        public async Task<object> QueryCurrentProjectsEnvironmentReport(QB_ProjectEnvironmentsInput input)
        {
            var entity = qb_projectEnvironmentsRepository.GetAll().Where(x => x.ProjectId == input.ProjectId)
                .OrderByDescending(x => x.RecordTime).Take(1).FirstOrDefault();

            var list = new dynamic[6];
            return await Task.FromResult(new[] {                
                //GetAvg(entity.HumidityTag,2, "当前湿度", ""),
                GetAvg(entity.Pm2p5Tag, 3, "当前PM2.5", "μg/m³"),
                GetAvg(entity.Pm10Tag, 4, "当前PM10", "μg/m³"),
                GetAvg(entity.NoiseTag, 5, "当前噪音", "分贝"),
                GetAvg(entity.WindSpeedTag, 6, "当前风速", "m/s"),
                GetAvg(entity.TemperatureTag, 1, "当前温度", "℃")
            });
        }

        private dynamic GetAvg(string value, int type, string name = "", string unit = "")
        {
            var val = JsonConvert.DeserializeObject<ReadingTag>(value);
            return new { Name = name, Value = val?.Avg + unit, type };
        }

        /// <summary>获取项目环境监控数据，统计报表</summary>
        [AbpAuthorize]
        public async Task<object> QueryProjectsEnvironmentReport(QB_ProjectEnvironmentsInput input)
        {
            var query = qb_projectEnvironmentsRepository.GetAll().Where(x => x.ProjectId == input.ProjectId)
                            .WhereIf(input.Range != RangeEnum._24小时, x => x.RecordTime.Hour == 0)
                            .OrderByDescending(x => x.RecordTime).Take(input.Range.GetHashCode()).ToList();

            var dict = new Dictionary<string, string>();
            for (int i = input.Range.GetHashCode(); i >= 0; i--)
            {
                var key = input.Range == RangeEnum._24小时 ? DateTime.Now.AddHours(-i).Hour + "时" : DateTime.Now.AddDays(-i).Day + "日";
                dict.Add(key + (dict.ContainsKey(key) ? " " : ""), ""); //24小时和30天会出现相同键，所以需要处理下
            }

            foreach (var item in query)
            {
                var key = input.GetUnit(item.RecordTime);
                if (dict.ContainsKey(key))
                    dict[key] = GetAvg(item.GetDataByType(input.Type), input.Type).Value;
            }

            if (input.DataType == 0) return await Task.FromResult(dict);
            else return await Task.FromResult(dict.ToArray());
        }

        /// <summary>
        /// 获取项目塔吊运行数据
        /// </summary>
        /// <param name="input">分页</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<PagedResultDto<QB_ProjectCranes>> QueryProjectsCranePagedList(QB_ProjectCranesInput input)
        {
            var query = qb_projectCranesRepository.GetAll()
                    .WhereIf(!input.SerialNumber.IsNullOrWhiteSpace(), x => x.SerialNumber.Contains(input.SerialNumber))
                    .WhereCraneRecordTimeRange(input.RecordTimeRange);

            var result = await query.OrderByDescending(x => x.RecordTime).PageByAsync(input);

            return new PagedResultDto<QB_ProjectCranes>(query.Count(), ObjectMapper.Map<List<QB_ProjectCranes>>(result));
        }

        /// <summary>
        /// 获取项目施工升降机运行数据
        /// </summary>
        /// <param name="input">分页</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<PagedResultDto<QB_ProjectLifts>> QueryProjectsLiftPagedList(QB_ProjectsLiftInput input)
        {
            var query = qb_projectLiftsRepository.GetAll()
                .WhereIf(!input.SerialNumber.IsNullOrWhiteSpace(), x => x.SerialNumber.Contains(input.SerialNumber))
                 .WhereLiftRecordTimeRange(input.RecordTimeRange);

            var result = await query.OrderByDescending(x => x.RecordTime).PageByAsync(input);

            return new PagedResultDto<QB_ProjectLifts>(query.Count(), ObjectMapper.Map<List<QB_ProjectLifts>>(result));
        }

        /// <summary>
        /// 获取项目视频监控摄像头数据
        /// </summary>
        /// <param name="input">分页</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<PagedResultDto<QB_ProjectVideosDto>> QueryProjectsVideoList(QB_ProjectVideosInput input)
        {
            var query = qb_projectVideosRepository.GetAll().Where(x => x.ProjectId == input.ProjectId);
            var result = await query.OrderByDescending(x => x.CreationTime).PageByAsync(input);

            return new PagedResultDto<QB_ProjectVideosDto>(query.Count(), ObjectMapper.Map<List<QB_ProjectVideosDto>>(result));
        }

        /// <summary>根据视频标识获取视频详细信息</summary>
        [AbpAuthorize]
        public async Task<object> QueryVideoDetailById(EntityDto<Guid> input)
        {
            var result = await qb_projectVideosRepository.FirstOrDefaultAsync(x => x.Id == input.Id);
            return ObjectMapper.Map<QB_ProjectVideosDto>(result);
        }

        /// <summary>
        /// 根据摄像头获取播放地址
        /// </summary>
        /// <param name="input">视频标识</param>
        /// <returns></returns>
        [AbpAuthorize]
        public async Task<QB_ProjectVideoPlays> QueryProjectsVideoPlay(Guid input)
        {
            return await qb_projectVideoPlaysRepository.GetAsync(input);
        }

        #endregion

        ///// <summary>
        ///// 同步千变数据并保存至本地数据库
        ///// </summary>
        ///// <param name="code">枚举（项目1 / 考勤2 / 设备3 / 环境4 / 全部0）</param>
        ///// <returns></returns>
        //[RemoteService(false)]
        //public async Task AsyncQianbianData(EnumEventArg code = 0)
        //{
        //    if (code == 0)
        //    {
        //        await RequestAsyncCache.GetAsync(60, async () =>
        //        {
        //            await EventBus.TriggerAsync(new QianbianSyncEvent(code));
        //            return true;
        //        });
        //    }
        //    else
        //    {
        //        await EventBus.TriggerAsync(new QianbianSyncEvent(code));
        //    }
        //}

        /// <summary>同步千变数据并保存至本地数据库</summary>
        public async Task Async1()//保持方法名简短模糊，避免暴露敏感功能
        {
            await RequestAsyncCache.GetAsync(60, async () =>
            {
                await EventBus.TriggerAsync(new QianbianSyncEvent(0));
                return true;
            });
        }

        /// <summary>清空部分千变数据，并重新同步数据</summary>
        public async Task Async2()//保持方法名简短模糊，避免暴露敏感功能
        {
            await RequestClearCache.GetAsync(60, async () =>
            {
                //验证远程服务器是否正常，只有正常时才清空数据
                var list = await GetProjectPagedList(0, 1);
                if (!list.Items.Any()) return false;

                try
                {
                    //await qb_projectEnvironmentsRepository.DeleteAsync(x => true);
                    //await qb_projectAttendancesRepository.DeleteAsync(x => true);
                    //await qb_projectCranesRepository.DeleteAsync(x => true);
                    //await qb_projectDevicesRepository.DeleteAsync(x => true);
                    //await qb_projectLiftsRepository.DeleteAsync(x => true);
                    await qb_projectVideoPlaysRepository.DeleteAsync(x => true);
                    await qb_projectVideosRepository.DeleteAsync(x => true);
                    await qb_projectUsersRepository.DeleteAsync(x => true);
                    await qb_projectsRepository.DeleteAsync(x => true);
                }
                finally
                {
                    await Async1();
                }

                return true;
            });
        }
    }
}
